# -*- coding: utf-8 -*-
import datetime
import orjson
from typing import Any, Callable, Dict, Optional
from sqlalchemy import Row


def has_func(obj, func):
    return hasattr(obj, func) and callable(getattr(obj, func))


# 当遇到不可序列化时，会调用
def default_serializer(obj: Any) -> Any:
    if isinstance(obj, datetime.datetime):
        return obj.strftime("%Y-%m-%d %H:%M:%S")
    if obj:
        if isinstance(obj, Row):
            return dict(obj._asdict())
        if has_func(obj, 'to_dict'):
            return obj.to_dict()

    raise TypeError(f"Type {type(obj).__name__} is not serializable")


def remove_null_values(data):
    if isinstance(data, dict):
        for key, value in data.items():
            if value in (None, '', [], {}):
                del data[key]
            else:
                remove_null_values(value)
    elif isinstance(data, list):
        for i, item in enumerate(data):
            if item in (None, '', [], {}):
                del data[i]
            else:
                remove_null_values(item)


def object_pairs_hook(pairs: Dict[str, Any]) -> Any:
    for key, value in pairs.items():
        if isinstance(value, str):
            try:
                pairs[key] = datetime.datetime.fromisoformat(value)
            except ValueError:
                pass
    return pairs


def orjson_loads(s: str) -> Any:
    return orjson.loads(s)


def orjson_dumps(obj: Any, *, option: Optional[int] = None, exclude_null=True, exclude_empty_obj=False) -> bytes:
    return orjson.dumps(obj, option=option, default=default_serializer)




"""
# 示例使用
now = datetime.datetime.now()
serialized = dumps(now)  # 序列化时间对象
print(serialized)  # 输出: 字节串表示的 JSON

deserialized = loads(serialized)  # 反序列化 JSON 字节串
print(deserialized)  # 输出: 时间对
"""